package com.authine.cloudpivot.web.api.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author jiangcai.zjc
 * @date 2020/02/06
 */
@Component
public class CookieUtil {

    private static final Logger log = LoggerFactory.getLogger(CookieUtil.class);

    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = Optional.ofNullable(request.getCookies()).orElse(new Cookie[] {});
        //添加开关，用于排查问题时，打开cookie打印
        if (log.isDebugEnabled()) {
            printCookie(cookies);
        }

        return Arrays.stream(cookies)
            .filter(cookie -> cookieName.equals(cookie.getName()))
            .findFirst().orElse(null);
    }

    /**
     * 从request的cookie中获取sessionId
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String readValueFromCookie(HttpServletRequest request, String cookieName) {
        Cookie selectedCookie = getCookie(request, cookieName);
        if (selectedCookie == null) {
            return null;
        }

        return selectedCookie.getValue();
    }

    /**
     * debug出来端上的cookie
     *
     * @param cookies
     */
    private static void printCookie(Cookie[] cookies) {
        if (cookies == null || cookies.length < 1) {
            log.debug("printCookie.cookies.length is empty");
            return;
        }
        List<Map<String, String>> mapList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            Map<String, String> logMap = new HashMap<>();
            if (cookie == null) {
                continue;
            }
            logMap.put("domain", cookie.getDomain());
            logMap.put("name", cookie.getName());
            logMap.put("maxAge", String.valueOf(cookie.getMaxAge()));
            logMap.put("value", cookie.getValue());
            mapList.add(logMap);
        }
        log.debug("打印client端的cookie信息|{}", mapList);
    }

    public static void writeCookie(HttpServletResponse response, String cookieName, String cookieValue,
        String cookieDomain) {
        Cookie cookie = buildCookie(cookieName, cookieValue, cookieDomain);
        cookie.setMaxAge(-1);

        //httpOnly=true 表示JS不能读写HttpOnly Cookie
        cookie.setHttpOnly(true);

        //secure=true —— 只能在HTTPS连接中传输，HTTP连接不会传输，所以不会被窃取到Cookie的具体内容
        //false —— HTTP、HTTPS连接都可以传输
        cookie.setSecure(false);

        response.addCookie(cookie);
    }

    @NotNull
    public static Cookie buildCookie(String cookieName, String cookieValue, String cookieDomain) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath("/");
        if (StringUtils.isNotEmpty(cookieDomain)) {
            cookie.setDomain(cookieDomain);
        }
        return cookie;
    }

    public static void deleteCookie(HttpServletResponse response, String cookieName, String cookieDomain) {
        Cookie cookie = buildCookie(cookieName, "", cookieDomain);
        deleteCookie(response, cookie);
    }

    public static void deleteCookie(HttpServletResponse response, Cookie cookie) {
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}
